<?



 $err=0;
 $warn=0;
 ini_set('max_execution_time',0);
 @set_time_limit(0);
 ini_set('auto_detect_line_endings',1);
 restore_include_path();

 session_start();

 if($_GET['restart']){
  unset($_SESSION['ini']);
	header("Location: ".$PHP_SELF);
	exit;
}	

 
 /*
  * mysql < dump.sql
  */
 function file_to_db($filename){

   if(!$lines=file($filename)){
     echo "<div class=err>ERROR: can not read $filename</div>";
     return 0;
   }

   foreach($lines as $l){
     if(preg_match("/^\s*(#|--)/",$l)){
       //do no
     }else if(preg_match("/;\s*$/",$l)){
       $query=$query.substr($l,0,-1);
       if(!mysql_query($query)){
         echo "<div class=err>ERROR: cannot execute database query</div>
	 <pre>
	 $query
	 </pre>";
         return 0;
       }
       $query='';
     }else{
       $query=$query.$l;
     }
   }

   return 1;
 }

?>
<html>
<head>
<title>phpMyTicket installation</title>
<style>
  .err {color:#dd0000;}
  .warn {color:#cc9900;}
  .ok {color:#00dd00;}
</style>
</head>
<body>

<?

if($_POST['install'] and $_POST['inst_button']){

	$install_dir=$_SESSION['ini']['install_dir'];
	$includes_dir=$install_dir."/includes";
	
  if(!$init_common=file_get_contents("$install_dir/inst/init_common.php"))
  {
    echo "<div class='err'>Cannot read configuration file <i>
		$install_dir/inst/init_common.php</i></div>";
		exit;
  }else{
    function callback($matches){
      return $_SESSION['ini'][$matches[1]];
    }

    $_SESSION['ini']['install_dir_esc']=addslashes($_SESSION['ini']['install_dir']);
    $_SESSION['ini']['full_include_path']=get_include_path().PATH_SEPARATOR.$_SESSION['ini']['install_dir'];

		if($_SESSION['ini']['install_mode']=='install'){
		  $_SESSION['ini']['old_organizer_id']=3;
		}
		
    $init_common=preg_replace_callback("/%(\w+)%/","callback",$init_common);

    if(!$fh=fopen("$includes_dir/config/init_common.php",'w') or
       !fwrite($fh,$init_common) or
       !fclose($fh))
    {
      echo "<div class=err>Can not write configuration file $includes_dir/config/init_common.php</div>";
			exit;
    }
	}

	
	
	if(!mkdir("$includes_dir/tmp/web") or
		 !mkdir("$includes_dir/tmp/web/templates_c") or
		 !mkdir("$includes_dir/tmp/web/cache") or
		 !mkdir("$includes_dir/tmp/pos") or
		 !mkdir("$includes_dir/tmp/pos/templates_c") or
		 !mkdir("$includes_dir/tmp/pos/cache"))
  {
      echo "<div class=warn>WARNING: can not create temporary folders under 
                           $includes_dir/tmp</div>";
			$warn++;										 
  }
    		
  if(!(mysql_connect($_SESSION['ini']['db_host'],$_SESSION['ini']['db_uname'],
                   $_SESSION['ini']['db_pass']) and       
									 mysql_select_db($_SESSION['ini']['db_name'])))
  {
		echo "<div class=err>ERROR: can not connect to the database</div>";
		exit;
	}


	if($_SESSION['ini']['install_mode']=='install'){
		
		//import contens of mysqldump to db
		if(file_to_db("$install_dir/inst/phpMyTicket.sql")){
      echo "<div class=ok>Database structure created</div>";
		}else{
			echo "<div class=err>ERROR: can not create database structure!</div>";
			exit;
		}

		//create admin user
		$query ="update Admin set
						 admin_login='{$_SESSION['ini']['admin_login']}',
						 admin_password=md5('{$_SESSION['ini']['admin_password']}')
						 where
						 admin_id='3' and
						 admin_status='organizer'";   


		if(mysql_query($query)){
			echo "<div class=ok>Admin user created</div>";
		}else{
			echo "<div class=err>ERROR: Admin user can not be created!</div>";
			exit;
		}

		//force recompile of templates   
		$query ="UPDATE Template set template_status='new'";   
		mysql_query($query);

		//because of a bug on my mac!
		$query ="ALTER TABLE `order` RENAME `Order`";   
		mysql_query($query);

	}

	else if($_SESSION['ini']['install_mode']=='update'){
		
		//import contens of mysqldump to db
		if(file_to_db("$install_dir/inst/update.sql")){
      echo "<div class=ok>Database structure updated</div>";
		}else{
			echo "<div class=err>ERROR: can not update database structure!</div>";
			exit;
		}

		//delete other users
		$query="delete from Admin where admin_id!='{$_SESSION['ini']['old_organizer_id']}'";
		mysql_query($query);
  
		//delete other users
		$query="delete from Organizer where organizer_id!='{$_SESSION['ini']['old_organizer_id']}'";
		mysql_query($query);

		//create admin user
		$query ="update Admin set
						 admin_login='{$_SESSION['ini']['admin_login']}',
						 admin_password=md5('{$_SESSION['ini']['admin_password']}')
						 where
						 admin_id='{$_SESSION['ini']['old_organizer_id']}' and
						 admin_status='organizer'";   


		if(mysql_query($query)){
			echo "<div class=ok>Admin user created</div>";
		}else{
			echo "<div class=err>ERROR: Admin user can not be created!</div>";
			exit;
		}

		//create admin user
		$query ="update Organizer set
						 organizer_nickname='{$_SESSION['ini']['admin_login']}'
						 where
						 organizer_id='{$_SESSION['ini']['old_organizer_id']}'";   


		if(mysql_query($query)){
			echo "<div class=ok>Admin user created</div>";
		}else{
			echo "<div class=err>ERROR: Admin user can not be created!</div>";
			exit;
		}

		
		//force recompile of templates
		$query ="UPDATE Template set template_status='new'";   
		mysql_query($query);
	}
	
	
  if(!$err){
		
		if(!$warn){
      echo "<h1 class=ok>phpMyTicket was successfully installed</h1><hr><br>";
		}else{
      echo "<h1 class=warn>phpMyTicket was parially installed, with warnings!</h1><hr>
			Maybe it will not work!!! 
			<br>";
		}	

		if($_SESSION['ini']['install_mode']=='update'){
			echo"<b>Attention!</b> If you have modified original smarty templates, 
			you will need to move and adapt them. To finish the update please read  
			<a href='update'>update instructions</a>.";
			
		}else{
			
			echo"<b>Attention</b> Demo users was created for control and salepoint interfaces with login <i>demo</i>
			, password <i>demodemo</i>. <b>Please change those passwords in admin interface!!!</b>";
		}	

		
		echo"
<div>For the security reasons you should put this file to read-only by webserver: <br>
<br> <tt>includes/config/init_common.php</tt></div>
<div>You also have to delete the <tt>inst</tt> folder.</div>
<br><br>     

<li><a href='../admin/index.php' target='pmt_1'>Go to Admin</a>. <br>
<li><a href='../index.php' target='pmt_2'>Go to Demo Shop</a> <br>
<li><a href='../pos/index.php' target='pmt_3'>Go to Demo Sale Point</a><br>
<li><a href='../control/index.php' target='pmt_4'>Go to Demo Ticket Control Point</a><br>


<br><br>
Please, say us if you run phpmyticket on your site : 
add your site to <a href='http://www.phpmyticket.com/en/live.html' target='_new'>'Live Sites'</a> page or
send us an email to <i>info at phpmyticket dot com</i> !
<br><br>
Please, don't remove 'Powered by phpMyTicket' link.
<br><br>

			<pre>
************************************************
**                                            **
** Please, help us to promote phpmyticket by: **
**                                            **
** - testing and using it!                    **
** - finding (and even fixing!) bugs          **
** - linking to phpmyticket.com               **
** - speaking to your friends about it        **
** - providing feedback                       **
** - providing any other help and support     **
**                                            **
************************************************			
			
			</pre>";

			session_destroy();
      exit;
    }else{
      echo "<h1 class=err>phpMyTicket installation failed</h1><hr>
            <a href=''>Change parameters and try again?</a>";
			exit;
    }
  

}else if($_POST['back_button']){
  unset($_SESSION['ini']);
}

?>
<h1>Welcome to phpMyTicket installation script!</h1>
<hr>

<? 
if(function_exists("mysqli_connect")) { 
   echo "MySQLi is installed!"; 
} else { 
   echo "MySQLi is not installed..."; 
} 


//chechk php version


if(!$_SESSION['ini']['php_version']){
  $ver = explode('.',phpversion());
    if($ver[0]!=4){
      echo "<li><span class='err'>FAILED: php version 4 is required, You have php version ".phpversion()."</span></li>";
      $err++;
    }else if($ver[1]<3 or $ver[2]<3){
      echo "<li><span class='warn'>WARNING: this program was tested with php version 4.3.3 or more. You have php version ".phpversion().". Probably this is not a problem.</span ></li>";
      $warn++;
   }else{
     echo "<div class=ok>php version is OK</div>";
     $_SESSION['ini']['php_version']=1;
   }
}



?>

<form action="" method="post">
<h4>New Install or Update?</h4>
Please choose if this is a new install or an update <b>from phpMyTicket-0.2</b>.<br> 
If you choose the update you should provide
valid access parameters to your existing database.<br>
If you have modified default templates, you will have to move them by hand.<br>
<li><b>NB 1</b> Update is only possible from v.0.2 (not from v.0.1.x)! <br>
<li><b>NB 2</b> The update modifies the database, you should <b>BACKUP</b> your database before doing update!<br><br>

<?

if($_POST['install_mode']){
  $_SESSION['ini']['install_mode']=$_POST['install_mode'];
}

if(!$install_mode=$_SESSION['ini']['install_mode']){
  $install_mode='install';
}

$chk[$install_mode]='checked';

echo "
<label><input type='radio' name='install_mode' value='install' ".$chk['install']."> New installation</label><br>
<label><input type='radio' name='install_mode' value='update' ".$chk['update']."> Update from v.0.2</label><br>
";
?>

<h4>Main directory</h4>
There is the directory where phpMyAdmin is installed. Fix if incorrect:<br>

<?
if($_POST['install_dir']){
  $_SESSION['ini']['install_dir']=$_POST['install_dir'];
}

if(!$install_dir=$_SESSION['ini']['install_dir']){
  $cwd=getcwd();
  $install_dir=substr($cwd,0,-5);
}
echo "<input name='install_dir' value='$install_dir' size='50'>";

if(!is_writable("$install_dir/includes/config/init_common.php")){
  echo "<div class=err>$install_dir/includes/config/init_common.php should be writable by the webserver user.</div> Please change the permissions of this file<br>";
  $err++;
}

if(!is_writable("$install_dir/includes/fonts")){
  echo "<div class=err>$install_dir/includes/fonts should be writable by the webserver user.</div> Please change the permissions of this directory<br>";
  $err++;
}

if(!file_exists("$install_dir/includes/tmp") and is_writable($install_dir."/includes") and mkdir("$install_dir/includes/tmp")){
  //thats ok
}else if(!is_writable("$install_dir/includes/tmp")){
  echo "<div class=err>$install_dir/includes/tmp should be writable by the webserver user.</div> Please change the permissions of this directory<br>";
  $err++;
}

if(!file_exists("$install_dir/files") and is_writable($install_dir) and mkdir("$install_dir/files")){
  //thats ok
}else if(!is_writable("$install_dir/files")){
  echo "<div class=err>$install_dir/files should be writable by the webserver user.</div> Please change the permissions of this directory<br>";
  $err++;
}

?>

<h4>Base URL</h4>
This is the URL of phpMyTicket files. Fix if incorrect:<br>

<?
if($_POST['root']){
  $_SESSION['ini']['root']=$_POST['root'];
}

if(!$root=$_SESSION['ini']['root']){
	$root ="http://".$_SERVER['HTTP_HOST'];
  $root .= substr($_SERVER['SCRIPT_NAME'],0,-14);
}
echo "<input name='root' value='$root' size='50'>";

?>


<h4>Database connection</h4>
In order to run phpMyTicket a database should be created. 
Please create the database and provide access parameters here. For the update: 
please provide parameters of existing phpMyTicket database.
<table>

<?

if($_POST['db_host']){
  $_SESSION['ini']['db_host']=$_POST['db_host'];
}

if($_POST['db_name']){
  $_SESSION['ini']['db_name']=$_POST['db_name'];
}

if($_POST['db_uname']){
  $_SESSION['ini']['db_uname']=$_POST['db_uname'];
}

if($_POST['db_pass']){
  $_SESSION['ini']['db_pass']=$_POST['db_pass'];
}

if(!$_SESSION['ini']['db_host']){
  $db_host='localhost';
}else{
  $db_host=$_SESSION['ini']['db_host'];
}

echo "
<tr><td>Database host</td><td><input type=text name='db_host' value='$db_host'></td></tr>
<tr><td>Database name</td><td><input type=text name='db_name' value='{$_SESSION['ini']['db_name']}'></td></tr>
<tr><td>Database user name</td><td><input type=text name='db_uname' value='{$_SESSION['ini']['db_uname']}'></td></tr>
<tr><td>Database password</td><td><input type=text name='db_pass' value='{$_SESSION['ini']['db_pass']}'></td></tr>
</table>
";
if($_SESSION['ini']['db_host'] and $_SESSION['ini']['db_uname'] and $_SESSION['ini']['db_name']){
  if($db=mysql_connect($_SESSION['ini']['db_host'],$_SESSION['ini']['db_uname'],$_SESSION['ini']['db_pass'])){
    if(mysql_select_db($_SESSION['ini']['db_name'])){
      echo "<div class='ok'>Database connection verified OK</div>";

      if($res=mysql_query("show variables like 'have_innodb'") and $v=mysql_fetch_row($res) and $v[1]=='YES'){
        echo "<div class=ok>InnoDB is supported by your mysql server</div>";
        
				if($install_mode=='install'){
					if($res=mysql_list_tables($_SESSION['ini']['db_name']) and mysql_fetch_row($res)){
						 echo "<div class=err>ERROR: Selected database {$_SESSION['ini']['db_name']} is <b>not empty</b>!</div>";
						 $err++;
					} 
				}

				if($install_mode=='update'){
					if($res=mysql_list_tables($_SESSION['ini']['db_name']) and !mysql_fetch_row($res)){
						 echo "<div class=err>ERROR: Selected database {$_SESSION['ini']['db_name']} is <b>empty</b>!</div>";
						 $err++;
					} 
				}

      }else{
        echo "<div class=err>InnoDB is not supported by your mysql server. myPhpTicket requires innodb!</div>";
        $err++;
      }
    }else{
      echo "<div class='err'>Database server connection OK, but cannot use specified database</div>";
      $err++;
    }
  }else{
      echo "<div class='err'>Database server connection FAILED</div>";
      $err++;
  }
}else{
 $err++;
}

?>

	<h4>Admin login and password</h4>
	
	Please choose the username and the password for the phpMyTicket super user<br>
  (Choose it even if you update, this will be your new login / password )<br>	
	<table>
	
	<?
	
	if($_POST['admin_login']){
		$_SESSION['ini']['admin_login']=$_POST['admin_login'];
	}
	
	if($_POST['admin_password']){
		$_SESSION['ini']['admin_password']=$_POST['admin_password'];
	}
	
	echo "
	<tr><td>Admin login</td><td><input type=text name='admin_login' value='{$_SESSION['ini']['admin_login']}'></td></tr>
	<tr><td>Admin password (at least 6 letters)</td><td><input type=text name='admin_password' value='{$_SESSION['ini']['admin_password']}'></td></tr>
	</table>
	";
	
	
	if(isset($_SESSION['ini']['admin_login']) and isset($_SESSION['ini']['admin_password'])){
		if(strlen($_SESSION['ini']['admin_login'])==0){
			echo "<div class=err>Please choose admin login</div>";
			$err++;
		}
	
		if(strlen($_SESSION['ini']['admin_password'])<6){
			echo "<div class=err>Admin password should be at least 6 letters long</div>";
			$err++;
		}
	}else{
		$err++;
	}



if($install_mode=='update'){
?>
	<h4>Default organizer</h4>
	phpMyTicket don't provide multi-organizer feature anymore. <br>
	You have to choose one organizer you want to keep.<br>
	You can find Organizer Nr. in 'Organizer' page in 
	the admin interface of phpMyTicket-0.2<br>	
	Be careful: other organizers will be deleted.<br>
<?

if($_POST['old_organizer_id']){
	if($_POST['old_organizer_id']>0){
		$_SESSION['ini']['old_organizer_id']=$_POST['old_organizer_id'];
	}else{
		echo "<div class=err>Please, provide numeric id </div>";
		$err++;		
	}	
}

if(!$old_organizer_id=$_SESSION['ini']['old_organizer_id']){
  $err++;
}

echo "<input type=text name='old_organizer_id' value='$old_organizer_id' size='4'>";

}
?>

<hr>
<?
if($err){
  echo "<div class=warn>Please provide missing values and fix errors.</div>";  
  echo "<input type='submit' value='Continue'>";
  echo "<input type='reset' value='Reset'>";
}else{
  echo "<div class=ok>You are ready to install! Do not change anything more!</div>"; 
  echo "<input type=hidden name=install value=1>";
  echo "<input type='submit' name='inst_button' value='Install it now'>";
  echo "<div>If you need to change some parameters type 'Go Back' instead.</div>";
  echo "<input type='submit' name='back_button' value='Go back'>";
} 
?>
</form>
<a href='?restart=1'>restart install</a>
</body>
</html>
